package com.ruoyi.common.utils.file;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.Hashtable;
import java.util.Random;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.core.io.ClassPathResource;

import java.text.SimpleDateFormat;

public class QRUtils {

    /**
     * 生成二维码
     * @param content
     * 二维码的值
     * @param logoFilePath
     * 传入空值表示不用Logo
     * @return
     */
    public static String GenerateQrImage(String content, String logoFilePath, String backgroundFilePath, int width) {
        String re = "";
        String localPath = RuoYiConfig.getProfile();
        String path = localPath+"/DailyFiles/QrCode/" + dateToStringFormat(new Date(), "yyyy-MM");
        String QrImagePath = writeQrImage(content, logoFilePath,backgroundFilePath, path, width);// 输出到文件
        re = Constants.RESOURCE_PREFIX + QrImagePath.substring(QrImagePath.indexOf("DailyFiles") - 1).replace("\\", "/");
        return re;
    }

    /*
     * 生成二维码--文件保存 返回文件保存完整路径
     */
    public static String writeQrImage(String content, String logoFilePath, String backgroundFilePath, String filepath, int width) {
        String QrImagePath = "";
        try {

            File folder = new File(filepath);
            if (!folder.exists()) {
                folder.mkdirs();
            }

            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();

            Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.MARGIN, 1); // 设置白边 0-4

            BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, width, hints);
            // bitMatrix = deleteWhite(bitMatrix);

            Random rd = new Random();
            File file1 = new File(filepath, dateToStringFormat(new Date(), "hhmmss") + "_" + rd.nextInt(1000) + ".jpg");

            // MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file1);
            BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
            if (StringUtils.isNotEmpty(logoFilePath)) {
                // Logo 图标存在
                Graphics2D gs = image.createGraphics();

                int ratioWidth = image.getWidth() * 2 / 10;
                int ratioHeight = image.getHeight() * 2 / 10;

                URL path = new URL(logoFilePath);
                Image img = ImageIO.read(path);
                int logoWidth = img.getWidth(null) > ratioWidth ? ratioWidth : img.getWidth(null);
                int logoHeight = img.getHeight(null) > ratioHeight ? ratioHeight : img.getHeight(null);

                int x = (image.getWidth() - logoWidth) / 2;
                int y = (image.getHeight() - logoHeight) / 2;

                gs.drawImage(img, x, y, logoWidth, logoHeight, null);
                gs.setColor(Color.black);
                gs.setBackground(Color.WHITE);
                gs.dispose();
                img.flush();
            }
            if (StringUtils.isNotEmpty(backgroundFilePath)) {
                // 背景
                // 加载背景图片
                File backgroundfile = new File(RuoYiConfig.getProfile()+backgroundFilePath);
                BufferedImage background = ImageIO.read(backgroundfile);

                // 创建Graphics2D对象，用于绘制前景图片
                Graphics2D g2d = background.createGraphics();

                // 确定合成位置
                int x = (background.getWidth() - image.getWidth()) / 2+18;
                int y = (background.getHeight() - image.getHeight()) / 2+86;

                // 绘制前景图片
                g2d.drawImage(image, x, y, null);

                // 释放画笔资源
                g2d.dispose();

                // 保存合成后的图片
                ImageIO.write(background, "JPEG", file1);
            } else
                ImageIO.write(image, "JPEG", file1);

            QrImagePath = file1.getPath();

            // LoveTools.ConsolePrint(QrImagePath);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return QrImagePath;
    }

    public static String dateToStringFormat(Date dt, String format) {
        SimpleDateFormat formatter;
        formatter = new SimpleDateFormat(format);
        String cdt = formatter.format(dt);
        return cdt;
    }

    public static BufferedImage getStreamQrCode(String urlCode,String text) throws IOException {
        try {
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            //设置二维码图片宽高
            BitMatrix bitMatrix1 = qrCodeWriter.encode(urlCode, BarcodeFormat.QR_CODE, 300, 300);
            BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix1);

            // 创建Graphics2D对象
            Graphics2D g2d = image.createGraphics();

            // 设置字体和颜色
            Font font = new Font("宋体", Font.BOLD, 15);
            g2d.setFont(font);
            g2d.setColor(Color.BLACK);

            // 计算文本的位置（在图片底部）
            int x = 35 ; // 文本距离左侧的距离
            int y = image.getHeight() - font.getSize();

            // 添加文本
            g2d.drawString(text, x, y);

            return image;
        }
        catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
